package com.sec.android.app.myfiles.thumbnail;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.feature.Hover.AudioHoverView;
import com.sec.android.app.myfiles.feature.Hover.PlayableMediaHoverView;
import com.sec.android.app.myfiles.feature.Hover.VideoHoverView;
import com.sec.android.app.myfiles.feature.HoverMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment.ActionModeType;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.util.DrawableMgr;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.Locale;

public class ThumbnailImageView extends ImageView {
    private int mBorderResId;
    private int mNoBorderResId;

    private static final int BorderNormal = 0;
    private static final int BorderIncludeFocus = 1;
    private static final int None = 3;

    private AbsMyFilesFragment mFragment;
    private Context mContext;
    private View mFileIcon = null;
    private ImageView mPlayIcon = null;
    private View mNameText = null;
    private FileRecord mRecord = null;
    private View mGridNameBg = null;
    private boolean mIsGrid = false;
    private boolean mIsGridAlbum = false;
    private boolean mIsAirviewGrid = false;
    protected PlayableMediaHoverView mPlayableMediaHoverView = null;
    private boolean mIsRecentLastItem = false;

    public ThumbnailImageView(Context context) {
        this(context, null);
    }

    public ThumbnailImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ThumbnailImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        setBorderRes(attrs);
    }

    private void setBorderRes(AttributeSet attrs) {
        //int borderType = BorderNormal;
        int borderType = None;
        if (attrs != null) {
            borderType = attrs.getAttributeIntValue(AppConstants.MY_FILES_NAME_SPACE, "thumbnailBorderType", BorderNormal);
        }

        switch (borderType) {
            case None:
                mBorderResId = 0;
                mNoBorderResId = 0;
                break;
            case BorderIncludeFocus:
                mBorderResId = R.drawable.thumbnail_border_with_focus;
                mNoBorderResId = R.drawable.thumbnail_no_border_with_focus;
                break;
            case BorderNormal:
            default:
                mBorderResId = R.drawable.thumbnail_border;
                mNoBorderResId = 0;
                break;
        }
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        if (bm != null) {
            setImageDrawable(new BitmapDrawable(getResources(), bm));
        } else {
            setImageDrawable(null);
        }
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        // set a thumbnail to background for border
        super.setBackground(drawable);

        // set a thumbnail border to foreground
        if (drawable != null) {
            if (mBorderResId > 0) {
                setImageResource(mBorderResId);
            }

        } else {
            // removed code to check available resource id of mNoBorderResId.
            // because if resource id of no-boarder background is 0,
            // remove background.
            setImageResource(mNoBorderResId);
        }
        setVisible(drawable != null);
        setNameBgColor(drawable != null);
        setHoverListener(drawable != null);
    }

    private void setHoverListener(boolean hasThumbnail) {
        HoverMgr hover = HoverMgr.getInstance(mContext);
        if (hover != null && hover.isEnablePenHovering(mContext)) {
            if (mFragment != null) {
                if (mFragment.getNavigationInfo() != null) {
                    if (!mFragment.getNavigationInfo().isPickerMode() && HoverMgr.isSupportStorage(mRecord)) {
                        if (UiUtils.isCategoryFolderList(mContext)) {
                            HoverMgr.getInstance(mFragment.context()).setHoverListener(hasThumbnail ? this : mFileIcon, mRecord, mFragment, mContext);
                        } else if (mRecord.isPlayableFileType() && mFragment.getActivity() != null && !mIsRecentLastItem) {
                            if (mRecord.isVideoFileType()) {
                                mPlayableMediaHoverView = new VideoHoverView(mFragment.getActivity(), mFragment, mRecord);
                            } else {
                                mPlayableMediaHoverView = new AudioHoverView(mFragment.getActivity(), mFragment, mRecord);
                            }
                            this.setOnHoverListener(mPlayableMediaHoverListener);
                        } else if (mFragment.getActionModeType() == ActionModeType.NORMAL) {
                            if (hasThumbnail || isRecentLastItem()) {
                                HoverMgr.getInstance(mFragment.context()).setHoverListener(this, mRecord, mFragment, mContext);
                            } else if (isEnableHoverType()) {
                                HoverMgr.getInstance(mFragment.context()).setHoverListener(mFileIcon, mRecord, mFragment, mContext);
                            }
                        }
                    }
                }
            }
        }
    }

    private boolean isEnableHoverType() {
        boolean bRet = false;
        if (mRecord.getFileType() == FileType.FOLDER) {
            boolean showHidden = PreferenceUtils.getShowHiddenFiles(mContext);
            String currentFolderPath = mRecord.getFullPath();
            if (StorageMonitor.isSdCardPath(currentFolderPath) && !FileUtils.hasMediaScanSkipPath(currentFolderPath)) {
                int currentFolderHashCode = currentFolderPath.toLowerCase(Locale.US).hashCode();
                try (Cursor c = mContext.getContentResolver().query(FileUtils.MEDIA_PROVIDER_URI,
                        new String[]{MediaStore.Files.FileColumns.DISPLAY_NAME},
                        MediaStore.Images.ImageColumns.BUCKET_ID + "=" + currentFolderHashCode, null, null)) {
                    if (c != null) {
                        if (showHidden) {
                            bRet = (c.getCount() > 0);
                        } else {
                            while (c.moveToNext()) {
                                String displayName = c.getString(0);
                                if (!displayName.isEmpty() && !displayName.startsWith(".")) {
                                    bRet = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            } else {
                mRecord.initItemCount();
                if (mRecord.getItemCount(showHidden) > 0) {
                    bRet = true;
                }
            }
        } else if (mRecord.isAudioFileType() || mRecord.isDocumentFileType() || mRecord.isImageFileType()) {
            bRet = true;
        }
        return bRet;
    }

    public void setThumbnailView(AbsMyFilesFragment fragment, FileRecord record, View v) {
        mFragment = fragment;
        mRecord = record;
        mFileIcon = v.findViewById(R.id.file_type_icon);
        mGridNameBg = v.findViewById(R.id.file_detail_info);
        if ((record != null && (record.isVideoFileType() || record.isGear360Contents())) && mPlayIcon == null) {
            ViewStub playIconStub = (ViewStub) v.findViewById(R.id.play_icon_stub);
            if (playIconStub != null) {
                mPlayIcon = (ImageView) playIconStub.inflate();
            } else {
                mPlayIcon = (ImageView) v.findViewById(R.id.play_icon);
            }
        }
        mNameText = v.findViewById(R.id.file_name);
        mIsGrid = isGridList(v);
        mIsGridAlbum = isGridAlbumList(v);
        mIsAirviewGrid = isAirviewGridList(v);
    }

    public void setPlayIconVisible(boolean hasThumbnail) {
        if (mPlayIcon != null) {
            int visibility = View.GONE;
            int iconResId = -1;
            if (hasThumbnail) {
                if (mRecord.isGear360Contents()) {
                    iconResId = R.drawable.myfiles_list_btn_360_video_play;
                } else if (mRecord.isVideoFileType()) {
                    iconResId = (mRecord.getStorageType() == StorageType.Shortcut) ? R.drawable.myfiles_list_btn_play_shortcut : R.drawable.overlay_video_play_icon;
                }
                if (iconResId != -1) {
                    mPlayIcon.setImageDrawable(DrawableMgr.getDrawable(mContext, iconResId));
                    visibility = View.VISIBLE;
                }
            }
            mPlayIcon.setVisibility(visibility);
        }
    }

    public void setIsRecentLastItem(boolean isRecentLastItem) {
        mIsRecentLastItem = isRecentLastItem;
    }

    public boolean isRecentLastItem() {
        return mIsRecentLastItem;
    }

    private void setNameVisible(boolean hasThumbnail) {
        if (hasThumbnail) {
            mNameText.setVisibility(View.GONE);
        } else {
            mNameText.setVisibility(View.VISIBLE);
        }
    }

    public void setNameBgColor(boolean hasThumbnail) {
        int bgColorId;
        if (hasThumbnail) {
            bgColorId = R.color.category_grid_item_image_type_file_info_bg_color;
        } else {
            bgColorId = R.color.category_grid_item_icon_type_file_info_bg_color;
        }

        if (mGridNameBg != null && mIsGrid && !mIsGridAlbum) {
            mGridNameBg.setBackgroundResource(bgColorId);
        }
    }

    private boolean isGridList(View v) {
        boolean bRet = false;

        int id = v.getId();
        if (id == R.id.category_grid_item || id == R.id.recent_grid_item) {
            bRet = true;
        }
        return bRet;
    }

    private boolean isGridAlbumList(View v) {
        boolean bRet = false;

        int id = v.getId();
        if (id == R.id.category_grid_album_item) {
            bRet = true;
        }
        return bRet;
    }

    private boolean isAirviewGridList(View v) {
        boolean bRet = false;

        int id = v.getId();
        if (id == R.id.file_grid_item) {
            bRet = true;
        }
        return bRet;
    }

    private void setVisible(boolean hasThumbnail) {
        if (!hasThumbnail || (mFragment != null && mFragment.getNavigationInfo() != null && UiUtils.isCategoryFolderList(mFragment.getNavigationInfo().getCurRecord()))) {
            setPlayIconVisible(false);
        } else {
            setPlayIconVisible(true);
        }

        if (mIsAirviewGrid) {
            setNameVisible(hasThumbnail);
        }
    }

    private boolean isEnableRegisterHoverListener(MotionEvent ev) {
        boolean bRet = false;
        return bRet;
    }

    public View.OnHoverListener mPlayableMediaHoverListener = new OnHoverListener() {

        @Override
        public boolean onHover(View v, MotionEvent ev) {
            if (!isEnableRegisterHoverListener(ev))
                return false;

            if (ev.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS || (ev.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE && AppFeatures.isTabletUIMode())) {

                Rect hoverRect = new Rect();
                ((View) (v.getParent())).getGlobalVisibleRect(hoverRect);
                String path = mRecord.getFullPath();

                mPlayableMediaHoverView.setParam(v, hoverRect, path);

                switch (ev.getAction()) {
                    case MotionEvent.ACTION_HOVER_ENTER:
                        mPlayableMediaHoverView.sendDelayedMessage(500);
                        break;

                    case MotionEvent.ACTION_HOVER_EXIT:
                        mPlayableMediaHoverView.removeDelayedMessage();
                        break;

                    case MotionEvent.ACTION_HOVER_MOVE:
                        break;

                    default:
                        break;
                }
                return false;
            } else {
                return false;
            }
        }
    };
}
